<?php

namespace app\admin\controller\crm;

use app\admin\controller\BaseController;
use app\admin\logic\crm\CrmSettingsLogic;
use app\admin\validate\crm\CrmSettingValidate;
use support\Request;
use support\Response;

/**
 * CRM设置控制器
 * 用于管理客户资料分组和字段配置
 */
class CrmSettingsController extends BaseController
{
    /**
     * @var CrmSettingsLogic
     */
    protected $logic;

    /**
     * 构造
     */
    public function __construct()
    {
        parent::__construct();
        $this->logic = new CrmSettingsLogic();
    }

    public function getCrmSetting(Request $request) : Response {
        $groups = $this->logic->getGroupsWithFields();
        return $this->success($groups);
    }

    public function saveCrmSetting(Request $request) : Response {
        $params = $request->post('groups', []);
        // 验证输入数据格式
        if (!is_array($params) || empty($params)) {
            return $this->fail('无效的数据格式');
        }

        foreach ($params as $k => $group) {
            if (empty($group['fields'])) {
                return $this->fail('分组['.$group['name'].']必须包含至少一个字段');
            }
            $params[$k]['sort'] = $k+1;
        }

        $params = array_values($params);
        // 使用验证器进行严格数据验证
        $validate = new CrmSettingValidate();
        if (!$validate->check($params)) {
            return $this->fail($validate->getError());
        }
        try {
            $result = $this->logic->saveCrmSetting($params);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        if ($result) {
            return $this->success([], '保存成功');
        } else {
            return $this->fail('保存失败，请检查数据格式');
        }
    }
}
